package com.th.cash.th2.set

import androidx.lifecycle.viewModelScope
import com.th.basemodel.base.BaseViewModel
import com.th.basemodel.utils.AppUtil
import com.th.cash.storage.LocalSetting
import com.th.cash.th2.login.LoginRepository
import com.th.cash.th2.product.ProductDetailRequest
import com.th.cash.th2.product.ProductState
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
import kotlinx.coroutines.flow.debounce
class SetViewModel : BaseViewModel() {

    private val repository by lazy {
        SetRepository()
    }

    val intentChannel = Channel<SetIntent>(Channel.UNLIMITED)

    private val _uiState = MutableStateFlow<SetState>(SetState.Idle)
    val uiState: StateFlow<SetState> get() = _uiState

    init {
        viewModelScope.launch {
            intentChannel.consumeAsFlow().debounce(500).collect { value ->
                when (value) {
                    is SetIntent.Idle -> {
                        // Handle idle state
                    }

                    is SetIntent.Logout -> {
                        logout()
                    }
                }
            }
        }
    }


    private fun logout() {
        viewModelScope.launch {
            loadStartLoading()
            val result = repository.logout()

            result.checkResult(success = {
                loadSuccess()

                LocalSetting.userAdult = false
                LocalSetting.userSession = ""
                LocalSetting.userPhone = ""
                LocalSetting.userLogin = false

                AppUtil.sessionId = ""
                AppUtil.userPhone = ""

                _uiState.value = SetState.LogoutSuccess
            }, error = {
                loadError(it)
            })
        }
    }
} 